import 'package:flutter/material.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/pages/order/order_add/model/model_order_list.dart';
import 'package:flutter_yn_goods/utils/album_utils.dart';
import 'package:flutter_yn_goods/utils/http/api.dart';
import 'package:flutter_yn_goods/utils/http/http_manager.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class OrderReviewLogic extends GetxController {
  final ModelOrderList order = Get.arguments;

  final TextEditingController reviewController = TextEditingController();

  final RxInt productRating = 5.obs;
  final RxInt serviceRating = 5.obs;
  final RxBool isSubmitting = false.obs;

  // 存储上传的图片资源和URL
  final RxList<AssetEntity> selectedImages = <AssetEntity>[].obs;
  final RxList<String> uploadedImageUrls = <String>[].obs;

  // 选择图片
  Future<void> pickImages() async {
    final List<AssetEntity> images = await AlbumUtils.pickMultiImages(
      maxCount: 5,
      selectedAssets: selectedImages,
    );

    if (images.isNotEmpty) {
      selectedImages.value = images;
    }
  }

  // 删除选中的图片
  void removeImage(int index) {
    if (index >= 0 && index < selectedImages.length) {
      final List<AssetEntity> updatedList = List.from(selectedImages);
      updatedList.removeAt(index);
      selectedImages.value = updatedList;
    }
  }

  // 上传图片
  Future<bool> uploadImages() async {
    if (selectedImages.isEmpty) return true;

    uploadedImageUrls.clear();
    for (var asset in selectedImages) {
      final file = await asset.file;
      if (file == null) continue;

      final bytes = await file.readAsBytes();
      final fileName =
          "review_${DateTime.now().millisecondsSinceEpoch}.${file.path.split('.').last}";

      try {
        final response = await HttpManager().upload(
          fileData: bytes,
          fileName: fileName,
          requestId: order.id.toString(),
        );

        if (response.isSuccess && response.data != null) {
          uploadedImageUrls.add(response.data['url']);
        } else {
          LoadingUtils.showToast(LocaleKeys.upload_failed.tr);
          return false;
        }
      } catch (e) {
        LoadingUtils.showToast(LocaleKeys.upload_failed.tr);
        return false;
      }
    }

    return true;
  }

  // 提交评价
  Future<bool> submitReview() async {
    if (reviewController.text.trim().isEmpty) {
      LoadingUtils.showToast(LocaleKeys.enter_review.tr);
      return false;
    }

    isSubmitting.value = true;

    // 先上传图片
    if (selectedImages.isNotEmpty) {
      final success = await uploadImages();
      if (!success) {
        isSubmitting.value = false;
        return false;
      }
    }

    final params = {
      'id': order.id,
      'product_score': productRating.value,
      'service_score': serviceRating.value,
      'comment': reviewController.text.trim(),
      'pics': uploadedImageUrls.isNotEmpty ? uploadedImageUrls.join(',') : ''
    };

    try {
      final result = await HttpManager().post(
        API.leaderOrderComment,
        params: params,
      );
      isSubmitting.value = false;
      if (result.isSuccess) {
        LoadingUtils.showToast(LocaleKeys.review_success.tr);
        return true;
      } else {
        LoadingUtils.showToast(
            '${LocaleKeys.review_failed.tr}: ${result.message}');
        return false;
      }
    } catch (e) {
      isSubmitting.value = false;
      LoadingUtils.showToast(LocaleKeys.review_failed.tr);
      return false;
    }
  }

  @override
  void onClose() {
    reviewController.dispose();
    super.onClose();
  }
}
